import 'package:aichat_flutter_wallet/module/module_browser/provider/browser_proviser.dart';

import 'package:aichat_flutter_wallet/module/module_browser/viewmodel/we3_method.dart';

import 'package:aichat_flutter_wallet/module/module_browser/widget/dapp_select_chain.dart';

import 'package:aichat_flutter_wallet/module/module_browser/widget/dapp_select_node.dart';

import 'package:aichat_flutter_wallet/module/module_trade/widgets/triangle_painter.dart';

import 'package:aichat_flutter_wallet/module_common/provider/nav_key.dart';

import 'package:aichat_flutter_wallet/module_common/provider/wallet_info_provider.dart';

import 'package:aichat_flutter_wallet/module_common/utils/colors.dart';

import 'package:aichat_flutter_wallet/module_common/widgets/button/public_button.dart';

import 'package:aichat_flutter_wallet/module_common/widgets/dialog/bottom_sheet_widget.dart';

import 'package:aichat_flutter_wallet/module_common/widgets/image/public_image.dart';

import 'package:flutter/material.dart';

import 'package:flutter/cupertino.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import 'package:lib_database/lib_database.dart';

import 'package:lib_util/lib_util.dart';

import '../../../module_common/provider/token_list_provider.dart';

import 'package:decimal/decimal.dart';

class SelectNetwork extends StatefulWidget {
  final String? title;

  String? selectWalletName;

  SelectNetwork({super.key, this.title, this.selectWalletName});

  @override
  State<StatefulWidget> createState() {
    return _SelectNetworkState();
  }
}

class _SelectNetworkState extends State<SelectNetwork> {
  List<Chain> netWorkList = Web3MethodCall.getNetworkList();

  // List<NodeInfo> _nodeList = [];

  Chain? selectNetwork;

  Map<String, dynamic> blockMap = {};

  String walletShortName = '';

  late NodeInfo nodeInfoData;

  Wallet? curWallet = NavKey.getContext().read<WalletInfoNotifier>().wallet;

  String address = NavKey.getContext().read<WalletInfoNotifier>().walletAddress;

  List<Token> tokenList =
      NavKey.getContext().read<TokenListNotifier>().tokenList;

  @override
  void initState() {
    super.initState();

    if (widget.selectWalletName == null || widget.selectWalletName!.isEmpty) {
      walletShortName = context.read<WalletInfoNotifier>().walletChainShortName;
    } else {
      walletShortName = widget.selectWalletName!;
    }

    selectNetwork = netWorkList.firstWhere((element) {
      return element.shortName == walletShortName;
    });

    NodeInfo? nodeInfoData1 = context.read<BrowserProvider>().nodeInfoData;

    nodeInfoData = nodeInfoData1 ??
        ObjectBox().nodeInfoModel.getSelectedNodeInfo(walletShortName);

    doAsyncInit(nodeInfo: nodeInfoData);

    //  _nodeList = Web3MethodCall.getNodeList(walletShortName);
  }

  doConfirm() {
    Map<String, dynamic> map = {};

    map['chain'] = selectNetwork;

    map['node'] = nodeInfoData;

    map['block'] = blockMap;

    Navigator.of(context).pop(map);
  }

  // 选择网络返回

  changeNetWork(Chain value) {
    setState(() {
      selectNetwork = value;

      blockMap = {};
    });

    nodeInfoData =
        ObjectBox().nodeInfoModel.getSelectedNodeInfo(value.shortName);
    int walletId = context.read<WalletInfoNotifier>().walletId;
    WalletInfo? info = ObjectBox()
        .walletInfoModel
        .getWalletInfoByWalletIdAndChain(walletId, value.shortName);
    if (null != info) {
      context.read<WalletInfoNotifier>().updateCurrentWallet(info);
    }
    doAsyncInit(nodeInfo: nodeInfoData, needUpdateNode: true);
  }

  // 初始化

  doAsyncInit({required NodeInfo nodeInfo, bool needUpdateNode = false}) async {
    if (needUpdateNode) {
      if (mounted)
        setState(() {
          nodeInfoData = nodeInfo;
        });
    }

    // 有保存不用去拿

    // var blockMapProvider =

    var blockMap1 = await Web3MethodCall.getBlockHeight(nodeInfo.url);

    if (mounted)
      setState(() {
        blockMap = blockMap1;
      });

  }

// 点击节点返回页面

  doclickBack(value) {
    if (mounted)
      setState(() {
        nodeInfoData = value['node'];

        blockMap = value['block'];
      });
  }

  Widget select1() {
    return Column(
      children: [
        SizedBox(
          height: 10.w,
        ),
        InkWell(
          onTap: () {
            Web3MethodCall.selectNetwork(
                    child: DappSelectChainWidget(
                        walletShortName: selectNetwork!.shortName))
                .then((value) {
              if (value != null) {
                changeNetWork(value);
              }
            });
          },
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                'Select Network',
                style: TextStyle(
                    fontSize: 14.sp,
                    color: AppColors.c_333333,
                    fontWeight: FontWeight.w500),
              ),
              Image.asset(
                'assets/images/common/more.png',
                width: 12.w,
                height: 12.w,
              )
            ],
          ),
        ),
        SizedBox(
          height: 15.w,
        ),
        Container(
          padding: EdgeInsets.symmetric(horizontal: 15.w, vertical: 10.w),
          decoration: BoxDecoration(
              border: Border.all(width: 1.w, color: AppColors.c_E0E0E0),
              borderRadius: BorderRadius.all(Radius.circular(10))),
          child: Row(
            children: [
              ClipRRect(
                borderRadius: BorderRadius.circular(40.w),
                child: PublicImage(
                  image: selectNetwork!.logo,
                  width: 30.w,
                  height: 30.w,
                ),
              ),
              SizedBox(
                width: 8.w,
              ),
              Text(
                selectNetwork!.shortName,
                style: TextStyle(
                    fontSize: 14.sp,
                    color: AppColors.c_333333,
                    fontWeight: FontWeight.w500),
              )
            ],
          ),
        ),
        SizedBox(
          height: 20.w,
        ),
        InkWell(
          highlightColor: Colors.transparent,
          splashColor: Colors.transparent,
          onTap: () {
            Web3MethodCall.selectNetwork(
                    child: DappSelectNodeWidget(
                        walletShortName: selectNetwork!.shortName,
                        url: nodeInfoData.url))
                .then((value) {
              if (value != null) {
                doclickBack(value);
              }
            });
          },
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                'Select Node',
                style: TextStyle(
                    fontSize: 14.sp,
                    color: AppColors.c_333333,
                    fontWeight: FontWeight.w500),
              ),
              Image.asset(
                'assets/images/common/more.png',
                width: 12.w,
                height: 12.w,
              )
            ],
          ),
        ),
        SizedBox(
          height: 15.w,
        ),
        Container(
          padding: EdgeInsets.symmetric(horizontal: 15.w, vertical: 10.w),
          decoration: BoxDecoration(
              border: Border.all(width: 1.w, color: AppColors.c_E0E0E0),
              borderRadius: BorderRadius.all(Radius.circular(10.w))),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Expanded(
                child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        nodeInfoData.name ?? 'Official Node',
                        style: TextStyle(
                            fontSize: 14.sp,
                            fontWeight: FontWeight.w500,
                            color: AppColors.c_333333),
                      ),
                      SizedBox(
                        height: 2.w,
                      ),
                      Text(
                        nodeInfoData.url ?? 'Node Address',
                        style: TextStyle(
                            fontSize: 10.sp,
                            fontWeight: FontWeight.w400,
                            color: AppColors.c_BEBDCA),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      )
                    ]),
              ),
              Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Text(
                    blockMap.isNotEmpty ? '${blockMap['rate']}ms' : '--',
                    style: TextStyle(
                        fontSize: 12.sp,
                        color: blockMap.isNotEmpty
                            ? blockMap['color']
                            : AppColors.c_333333,
                        fontWeight: FontWeight.w400),
                  ),
                  SizedBox(
                    width: 5.w,
                  ),
                  if (blockMap.isNotEmpty)
                    Container(
                      width: 6.w,
                      height: 6.w,
                      decoration: BoxDecoration(
                          color: blockMap['color'],
                          borderRadius: BorderRadius.all(Radius.circular(3.w))),
                    )
                ],
              )
            ],
          ),
        ),
        SizedBox(
          height: 20.w,
        ),
        Stack(
          children: [
            Container(
              padding: EdgeInsets.symmetric(horizontal: 15.w, vertical: 10.w),
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.all(Radius.circular(5.w)),
                  color: Color.fromRGBO(134, 103, 254, 0.05),
                  border: Border.all(
                      color: Color.fromRGBO(134, 103, 254, 1), width: 1.w)),
              child: Row(
                // mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Expanded(
                    child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            curWallet != null ? curWallet!.name! : "MPC Wallet",
                            style: TextStyle(
                                fontSize: 14.sp,
                                fontWeight: FontWeight.w500,
                                color: AppColors.c_333333),
                          ),
                          SizedBox(
                            height: 2,
                          ),
                          Text(
                            curWallet != null ? address : "--",
                            style: TextStyle(
                                fontSize: 10.sp,
                                fontWeight: FontWeight.w400,
                                color: AppColors.c_BEBDCA),
                            overflow: TextOverflow.ellipsis,
                          )
                        ]),
                  ),
                  Text(
                    '\$${callBackAssets()}',
                    style: TextStyle(
                        fontSize: 16.sp,
                        fontWeight: FontWeight.w500,
                        color: AppColors.c_333333),
                  ),
                ],
              ),
            ),
            Positioned(
              bottom: 1.w,
              right: 1.w,
              child: CustomPaint(
                painter: DappTrianglePainter(),
                child: Container(
                  width: 20.w,

                  height: 20.w,

                  // color: Color.fromRGBO(134, 103, 254, 1),

                  alignment: Alignment.bottomRight,

                  child: Image.asset(
                    'assets/images/wallet-trade/selected.png', // 替换为你的图片路径

                    width: 14.w,

                    height: 14.w,
                  ),
                ),
              ),
            )
          ],
        ),
        SizedBox(
          height: 20.w,
        ),
        PublicButton(
          margin: EdgeInsets.zero,
          type: ButtonType.private,
          text: 'Comfirm',
          onClick: () {
            doConfirm();
          },
        )
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return BottomSheetWidget(
      title: widget.title ?? 'Select Network and Wallet',
      expand: false,
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 20.w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            select1(),
            SizedBox(
              height: 10.w + MediaQuery.of(context).padding.bottom.w,
            ),
          ],
        ),
      ),
    );
  }

  String callBackAssets() {
    if (tokenList.length <= 0) {
      return '0.00';
    }
    String result = tokenList.fold('0', (previousValue, element) {
      return Utils.formatDecimalBalance(
          Decimal.parse(previousValue) + Decimal.parse(element.valueusd ?? '0'),
          fractionDigits: Config.marketFixedNum);
    });
    return result;
  }
}
